package com.tech.security.securityservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tech.security.securityservice.mapper.PermMapper;
import com.tech.security.securityservice.mapper.UserMapper;
import com.tech.security.securityservice.model.LoginUser;
import com.tech.security.securityservice.model.Perm;
import com.tech.security.securityservice.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author sl
 */
@Service
public class SecurityUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermMapper permMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        User user = userMapper.selectOne(userQueryWrapper);;

        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }

        LoginUser loginUser = new LoginUser();
        loginUser.setId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        //根据用户查询权限信息 添加到LoginUser中
        List<Perm> perms= permMapper.findPermByUserId(user.getId());
        List<String> permsList = perms.stream().map(s -> s.getPerms()).collect(Collectors.toList());
        loginUser.setPermissions(permsList);
        return loginUser;
    }
}
